package org.jeecg.modules.demo.hd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.demo.hd.entity.AppMyProjectClickdetail;
import org.jeecg.modules.demo.hd.entity.AppUserGoldDetail;
import org.jeecg.modules.demo.hd.mapper.AppMyProjectClickdetailMapper;
import org.jeecg.modules.demo.hd.service.IAppMyProjectClickdetailService;
import org.jeecg.modules.demo.hd.service.IAppMyProjectDetailService;
import org.jeecg.modules.demo.hd.service.IAppUserGoldDetailService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * @Description: app_my_project_clickdetail
 * @Author: jeecg-boot
 * @Date: 2025-04-16
 * @Version: V1.0
 */
@Service
public class AppMyProjectClickdetailServiceImpl extends ServiceImpl<AppMyProjectClickdetailMapper, AppMyProjectClickdetail> implements IAppMyProjectClickdetailService {

    @Resource
    private IAppMyProjectDetailService myProjectDetailService;

    @Resource
    private IAppUserGoldDetailService goldDetailService;

    @Override
    @Transactional
    public String addDetail(AppMyProjectClickdetail model) {
        // 判断是否已经存在
        if (requestIdExist(model.getRequestId())) {
            return 0 + "";
        }
        model.setOriginalEcpm(Double.parseDouble(model.getEcpm()));
        Double currentUserDayGold = goldDetailService.getCurrentUserDayGold(); // 获取用户当天获得金币数量。
        double v =Double.parseDouble(model.getEcpm());
        if (model.getOriginalEcpm() > 400000) {
            v =  v* 0.5;
        } else if (currentUserDayGold > 3000000 && currentUserDayGold <= 5000000 && Double.parseDouble(model.getEcpm()) > 5000) {
            // 用户当天已经获取到40块钱以上80元一下，扣除平台费用20%
            v = v * 0.8;
        } else if (currentUserDayGold > 5000000 && Double.parseDouble(model.getEcpm()) > 5000) {
            // 用户当天已经获取到80块钱以上，扣除平台费用30%
            v = v * 0.7;  //3.5
        } else {
            v = v * 0.9;
        }
        if(v>200000) {
            v=v*0.8;
        }
        model.setEcpm(String.format("%.2f", v));
        this.save(model);
        // 判断用户当前完成点击次数，如果大于项目规定的次数，创建完成日志
        myProjectDetailService.updateUserProjectDetail(model);
        // 添加用户获得金币记录
        Integer goldNum = goldDetailService.addGoldDetail(model);
        return goldNum + "";
    }

    @Override
    public void clean() {
        this.baseMapper.delete(null);
    }

    @Override
    public Integer getCurrentUserClickCount() {
        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LocalDateTime startOfDay = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime endOfDay = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59).withNano(999999999);
        LambdaQueryWrapper<AppMyProjectClickdetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.between(AppMyProjectClickdetail::getCreateTime, startOfDay, endOfDay);
        queryWrapper.eq(AppMyProjectClickdetail::getUserId, currentUser.getId());
        int count = this.baseMapper.selectCount(queryWrapper).intValue();
        return count;
    }

    @Override
    public AppMyProjectClickdetail getLastClick() {
        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LocalDateTime startOfDay = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime endOfDay = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59).withNano(999999999);
        LambdaQueryWrapper<AppMyProjectClickdetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.between(AppMyProjectClickdetail::getCreateTime, startOfDay, endOfDay);
        queryWrapper.eq(AppMyProjectClickdetail::getUserId, currentUser.getId());
        queryWrapper.orderByDesc(AppMyProjectClickdetail::getCreateTime);
        Optional<AppMyProjectClickdetail> first = this.baseMapper.selectList(queryWrapper).stream().findFirst();
        if (first.isPresent()) {
            return first.get();
        }
        return null;
    }

    @Override
    public Integer getClickCountByDeviceId(String deviceId, String userId) {
        String day = DateUtils.getDate("yyyy-MM-dd");
        LambdaQueryWrapper<AppMyProjectClickdetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.apply("DATE_FORMAT(create_time,'%Y-%m-%d') = DATE_FORMAT({0},'%Y-%m-%d')", day);
        queryWrapper.eq(AppMyProjectClickdetail::getUserId, userId);
        queryWrapper.eq(AppMyProjectClickdetail::getDeviceId, deviceId);
        return this.baseMapper.selectCount(queryWrapper).intValue();
    }

    @Override
    public AppMyProjectClickdetail getLastClickDetail(String deviceId, String userId) {
        String day = DateUtils.getDate("yyyy-MM-dd");
        LambdaQueryWrapper<AppMyProjectClickdetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.apply("DATE_FORMAT(create_time,'%Y-%m-%d') = DATE_FORMAT({0},'%Y-%m-%d')", day);
        queryWrapper.eq(AppMyProjectClickdetail::getUserId, userId);
        queryWrapper.eq(AppMyProjectClickdetail::getDeviceId, deviceId);
        queryWrapper.orderByDesc(AppMyProjectClickdetail::getCreateTime);
        List<AppMyProjectClickdetail> list = this.baseMapper.selectList(queryWrapper);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    private boolean requestIdExist(String requestId) {
        LambdaQueryWrapper<AppMyProjectClickdetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppMyProjectClickdetail::getRequestId, requestId);
        int i = this.baseMapper.selectCount(queryWrapper).intValue();
        if (i > 0)
            return true;
        return false;

    }

}
